<template>
    <Row justify="space-between" :style="{ marginTop: '1px', verticalAlign: 'bottom', display: 'flex' }">
        <Col>
        <Tooltip title="上传食谱" color="blue">
            <Upload :multiple="true" :show-upload-list="false" :before-upload="handleBeforeUpload"
                class="upload-list-inline">
                <Button style="margin: 0 8px" shape="circle" :icon="h(UploadOutlined)"></Button>
            </Upload>
        </Tooltip>
        <Tooltip title="创建目录" color="blue">
            <Button style="margin: 0 8px" shape="circle" :icon="h(FolderAddOutlined)" @click="addFile"></Button>
        </Tooltip>
        <Tooltip title="创建食谱" color="blue">
            <Button style="margin: 0 8px" shape="circle" :icon="h(FileAddOutlined)" @click="addFood"></Button>
        </Tooltip>
        </Col>
        <Col>
        <Breadcrumb :style="{
            textAlign: 'right',
            margin: '0 18px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'flex-end',
        }">
            <BreadcrumbItem>
                <a href="#" @click.prevent="jump('')">根目录</a>
            </BreadcrumbItem>
            <BreadcrumbItem v-for="(part, index) in urls" :key="part">
                <a href="#" @click.prevent="jumpurl(index)">{{ part }}</a>
            </BreadcrumbItem>
        </Breadcrumb>
        </Col>
    </Row>
    <List v-if="filedata && filedata.length > 0" :style="{ padding: '10px 0px 10px 20px' }"
        :grid="{ gutter: 16, xs: 1, sm: 2, md: 4, lg: 4, xl: 6, xxl: 9 }" :data-source="filedata">
        <template #renderItem="{ item }">
            <Dropdown :trigger="['contextmenu']">
                <ListItem>
                    <a v-on:click="jump(item.keypath)">
                        <Tag v-text="item.name" color="blue" class="mb-2"></Tag>
                    </a>
                </ListItem>
                <template #overlay>
                    <Menu>
                        <MenuItem key="1" @click="clickFoodDir(item)">修改</MenuItem>
                        <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delFoodDirPost(item)">
                            <MenuItem key="2">删除</MenuItem>
                        </Popconfirm>
                    </Menu>
                </template>
            </Dropdown>
        </template>
    </List>
    <Row :gutter="24" justify="start" v-if="showTableView">
        <template v-for="item in data" :key="item.name">
            <Col :span="3" style="display: flex; justify-content: center; padding-bottom: 10px;">
            <Dropdown :trigger="['contextmenu']">
                <Card hoverable :style="{ width: '120px' }" @click="selfooddata(item)">
                    <template #cover>
                        <img :src="item.thumbnail" :style="{ width: '120px', height: '120px', objectFit: 'cover' }" />
                    </template>
                    <CardMeta :description="item.name">
                    </CardMeta>
                </Card>
                <template #overlay>
                    <Menu>
                        <MenuItem key="1" @click="setfoodimg(item)">
                        <Upload :show-upload-list="false" :before-upload="handleBeforeUploadThImg"
                            class="upload-list-inline">
                            设置封面
                            <!-- <Button style="margin: 0 8px" shape="circle" :icon="h(UploadOutlined)"></Button> -->
                        </Upload>
                        </MenuItem>
                        <!-- <MenuItem key="1" @click="setfoodimg(item)">设置封面</MenuItem> -->
                        <MenuItem key="2" @click="updatename(item)">设置名称</MenuItem>
                        <MenuItem key="3" @click="updatedata(item)">编辑内容</MenuItem>
                        <Popconfirm title="确定删除?" ok-text="确定" cancel-text="取消" @confirm="delfood(item)">
                            <MenuItem key="4">删除菜谱</MenuItem>
                        </Popconfirm>
                    </Menu>
                </template>
            </Dropdown>
            </Col>
        </template>
    </Row>
    <Pagination :style="{ float: 'right' }" v-model:current="params.currentPage" v-model:page-size="params.pageSize"
        :total="total" @change="onChange">
    </Pagination>
    <Modal @ok="submitFoodDir(true)" @cancel="submitFoodDir(false)" :title="fooddirTitle" v-model:open="openfooddir">
        <Form>
            <FormItem label="食谱目录名称">
                <Input v-model:value="params.name" />
            </FormItem>
        </Form>
    </Modal>
    <Modal @ok="submitFood(true)" @cancel="submitFood(false)" :title="foodTitle" v-model:open="openfood">
        <Form>
            <FormItem label="食谱名称">
                <Input v-model:value="params.name" />
            </FormItem>
        </Form>
    </Modal>
    <div v-if="showFoodView" class="mt-0">
        <Card title="Markdown">
            <template #extra><Button type="primary" @click="back"> 返回 </Button></template>
            <v-md-preview :text="valueRef"></v-md-preview>
        </Card>
    </div>
    <div v-if="showEditFoodView" class="mt-0">
        <Card title="Markdown Edit...">
            <template #extra>
                <Button type="primary" @click="back"> 返回 </Button>
                <Button type="primary" @click="saveFood" class="ml-2"> 保存 </Button>
            </template>
            <v-md-editor v-model="valueRef" height="750px" :include-level="[3, 4]" :disabled-menus="[]"
                @upload-image="handleUploadImage" @save="saveFoodData"></v-md-editor>
        </Card>
    </div>
</template>


<script lang="ts" setup>
import {
    FileAddOutlined,
    FolderAddOutlined,
    UploadOutlined,
} from "@ant-design/icons-vue";
import { ref, onBeforeMount, h } from "vue";
import { Api } from "../util/Api";
import { upload, post } from "../util/MyAxios";
import {
    Pagination,
    Popconfirm,
    Button,
    message,
    Row,
    Breadcrumb,
    BreadcrumbItem,
    Col,
    Card,
    Tooltip,
    Upload,
    Avatar,
    CardMeta,
    ListItem,
    List,
    Dropdown,
    Menu,
    MenuItem,
    Tag,
    Modal,
    Form,
    FormItem,
    Input,
} from "ant-design-vue";
const params = ref({
    path: "",
    keypath: "",
    name: "",
    oldname: "",
    newname: "",
    content: "",
    selname: "",
    currentPage: 1,
    pageSize: 16,
});
const data = ref<any>([]);
const total = ref(0);
const filedata = ref<any>();
const valueRef = ref(``);
const showTableView = ref(true);
const showFoodView = ref(false);
const showEditFoodView = ref(false);
const urls = ref<string[]>([]);
const openfooddir = ref<boolean>(false);
const fooddirTitle = ref("");
const openfood = ref<boolean>(false);
const foodTitle = ref("");
//分页切换页面
function onChange() {
    fetchData();
}
onBeforeMount(() => {
    fetchData();
});
async function fetchData() {
    await post(Api.Food_GetFoodPathInfo, params.value)
        .then((response) => {
            console.log(response.data);
            if (response.data != null && response.data.rows != null && response.data.rows.length > 0) {
                filedata.value = response.data.rows.filter((re) => re.isfolder);
                data.value = response.data.rows.filter((re) => !re.isfolder);
                total.value = response.data.total;
            } else {
                filedata.value = [];
                data.value = [];
                total.value = 0;
            }
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
            message.info(error.name + error.message + error.stack);
        });
}
const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append("file", file);
    if (params.value.path) {
        formData.append("fileurl", params.value.path);
    }
    return upload(Api.Food_UploadFood, formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    })
        .then((response) => {
            message.info("已上传:" + response.data);
            fetchData();
            return false;
        })
        .catch((error) => {
            console.error(error);
            return false;
        });
};
const handleBeforeUploadThImg = (file) => {
    console.log('handleBeforeUploadThImg');
    console.log(params.value.name);
    const formData = new FormData();
    formData.append("file", file);
    if (params.value.path) {
        formData.append("fileurl", params.value.path);
    }
    if (params.value.name) {
        formData.append("name", params.value.name);
    }
    return upload(Api.Food_UploadFoodThImg, formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    })
        .then((response) => {
            message.info("已上传:" + response.data);
            fetchData();
            return false;
        })
        .catch((error) => {
            console.error(error);
            return false;
        });
};


//获取文件内容数据
async function getFoodData() {
    await post(Api.Food_GetFoodData, params.value)
        .then((response) => {
            valueRef.value = response.data;
        })
        .catch((error) => {
            console.error(error);
        });
}
//保存食谱内容到服务器
async function saveFoodData() {
    params.value.content = valueRef.value;
    await post(Api.Food_SaveFoodData, params.value)
        .then((response) => {
            showMessage(response.data, "保存");
        })
        .catch((error) => {
            console.error(error);
        });
    params.value.content = "";
}
//创建一个新食谱
async function addFoodPost() {
    await post(Api.Food_AddFood, params.value)
        .then((response) => {
            showMessage(response.data, "添加食谱");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}
//删除一个食谱
async function delFoodPost(item) {
    11
    await post(Api.Food_DelFood, params.value)
        .then((response) => {
            showMessage(response.data, "删除食谱");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}
//删除一个食谱目录
async function delFoodDirPost(item) {
    params.value.name = item.name;
    await post(Api.Food_DelFoodDir, params.value)
        .then((response) => {
            showMessage(response.data, "删除食谱目录");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}
//创建一个食谱目录
async function addFoodDirPost() {
    await post(Api.Food_AddFoodDirectory, params.value)
        .then((response) => {
            showMessage(response.data !== "", "添加目录");
            if (response.data !== "") {
                urls.value.push(response.data);
                jumpurl(urls.value.length - 1);
            }
        })
        .catch((error) => {
            console.error(error);
        });
}
//修改食谱文件名称
async function editFoodNamePost() {
    await post(Api.Food_EditFoodDirOrName, params.value)
        .then((response) => {
            showMessage(response.data, "修改文件名称");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}

//修改食谱目录名称
async function editFoodDirNamePost() {
    await post(Api.Food_EditFoodDirOrName, params.value)
        .then((response) => {
            showMessage(response.data, "修改目录名称");
            fetchData();
        })
        .catch((error) => {
            console.error(error);
        });
}

function showMessage(result, prefix) {
    if (result) {
        message.success({
            content: prefix + "成功",
            duration: 2,
        });
    } else {
        message.error({
            content: prefix + "失败",
            duration: 2,
        });
    }
}

function jump(url) {
    params.value.path = url;
    if (url && url.length > 0) {
        urls.value = params.value.path.split("/");
    } else {
        urls.value = [];
    }
    fetchData();
}

//回到指定目录
function jumpurl(index) {
    let urlstr = "";
    let t = urls.value.length - 1 - index;
    if (t > 0) {
        for (let i = 0; i < t; i++) {
            urls.value.pop();
        }
    }
    for (let i = 0; i < urls.value.length; i++) {
        if (i <= index) {
            if (urlstr === "") {
                urlstr = urls.value[i];
            } else {
                urlstr = urlstr + "/" + urls.value[i];
            }
        }
    }
    params.value.path = urlstr;
    fetchData();
}

//文件大小格式转换
function getSize(length) {
    if (length === 0) return "0 B";

    const units = ["B", "KB", "MB", "GB", "TB"];
    let index = Math.floor(Math.log(length) / Math.log(1024));
    if (index > units.length - 1) index = units.length - 1;

    const convertedSize = length / Math.pow(1024, index);
    return convertedSize.toFixed(2) + " " + units[index];
}
//返回表格
function back() {
    showFoodView.value = false;
    showTableView.value = true;
    showEditFoodView.value = false;
}
//提交当前内容
function saveFood() {
    console.log("提交 食谱");
    saveFoodData();
}
//创建食谱
function addFood() {
    addFoodPost();
}
//新建目录
function addFile() {
    addFoodDirPost();
}

function clickFoodDir(item) {
    params.value.name = item.name;
    params.value.oldname = item.name;
    fooddirTitle.value = "修改食谱目录";
    openfooddir.value = true;
}
function submitFoodDir(b) {
    if (b) {
        params.value.newname = params.value.name;
        editFoodDirNamePost();
    }
    openfooddir.value = false;
    fetchData();
}
function submitFood(b) {
    if (b) {
        params.value.newname = params.value.name;
        editFoodNamePost();
    }
    openfood.value = false;
    fetchData();
}
//提交食谱图片
function handleUploadImage(event, insertImage, files) {
    // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
    if (files && files.length >= 1) {
        const formData = new FormData();
        formData.append("file", files[0]);
        upload(Api.Food_UploadFoodImg, formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        })
            .then((response) => {
                // showMessage(response.data, '上传图片');
                insertImage({
                    url: response.data,
                    desc: "",
                    // width: 'auto',
                    // height: 'auto',
                });
                console.log(response.data);
            })
            .catch((error) => {
                console.error(error);
            });
    }
}


function setfoodimg(item) {
    console.log('setfoodimg', item);
    params.value.name = item.name;
}
function delfood(item) {
    params.value.name = item.name;
    delFoodPost(item);
}
function updatename(item) {
    params.value.name = item.name;
    params.value.oldname = item.name;
    foodTitle.value = "修改食谱名称";
    openfood.value = true;
}
function updatedata(record) {
    console.log('updatedata', record);
    params.value.keypath = record.keypath;
    getFoodData();
    showTableView.value = false;
    showFoodView.value = false;
    showEditFoodView.value = true;
}
function selfooddata(record) {
    console.log('selfooddata', record);
    if (record.isfolder) {
        urls.value.push(record.name);
        jumpurl(urls.value.length - 1);
    } else {
        params.value.keypath = record.keypath;
        getFoodData();
        showTableView.value = false;
        showFoodView.value = true;
        showEditFoodView.value = false;
    }
}

</script>
